package top.kpromise.common.base;

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import lombok.experimental.Accessors;

import java.util.ArrayList;

@Data
@Accessors(chain = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Result<T> {

    private T data;
    private ArrayList<T> list;
    private PageInfo pageInfo;
    private String message = "请求成功";
    private Integer code = 100;

    public Result<T> error(Integer errorCode) {
        this.code = errorCode;
        this.message = "数据请求失败";
        return this;
    }

    public Result<T> error(Integer errorCode, String message) {
        this.code = errorCode;
        this.message = message;
        return this;
    }

    public static <R> Result<R> error(String message) {
        Result<R> result = new Result<>();
        result.error(101, message);
        return result;
    }

    public static <R> Result<R> error(Result result) {
        return new Result<R>().error(result.getCode(), result.getMessage());
    }

    public static <R> Result<R> data(R data) {
        return data(null, data);
    }

    public static <R> Result<R> data(String message, R data) {
        Result<R> result = new Result<>();
        result.setCode(100);
        if (message != null) {
            result.setMessage(message);
        } else {
            result.setMessage("操作成功");
        }
        result.setData(data);
        return result;
    }

    public static <R> Result<R> success(String message) {
        Result<R> result = new Result<>();
        result.setCode(100);
        result.setMessage(message);
        return result;
    }

    public boolean success() {
        return code == 100;
    }

    public <R> Result<R> toResult() {
        Result<R> result = new Result<>();
        result.setMessage(message);
        result.setCode(code);
        return result;
    }
}
